package com.stu.controller;

import com.stu.commons.ServerResponse;
import com.stu.pojo.Address;
import com.stu.pojo.Users;
import com.stu.service.IAddressService;
import com.stu.service.IUsersService;
import com.stu.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/address")
public class AddressController {
    @Autowired
    private IAddressService addressService;
    @Autowired
    private IUsersService usersService;

    @GetMapping
    public ServerResponse getAddressByUserId(HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String userId = JwtUtil.getUserIdFromToken(token);
        return addressService.getAddressByUserId(Integer.parseInt(userId));
    }

    @PostMapping
    public ServerResponse save(Address address, HttpServletRequest request) {
        String token = request.getHeader("Authorization").substring(7);
        String userIdStr = JwtUtil.getUserIdFromToken(token);
        Integer userId = Integer.parseInt(userIdStr); // 转换为 Integer

        address.setUserId(userId);
        Users user = (Users) usersService.getById(userId).getData();
        address.setAddressName(user.getUserNickname());
        address.setAddressTelno(user.getUserTelno());

        System.out.println("AddressController 新增的地址是：" + address);
        ServerResponse response = addressService.save(address);
        return response;
    }

}
